layui.define(['element', 'api', 'listener', 'amis', 'utils', 'action_executer'], function(exports) {
	"use strict";

	/**
	 * Button component
	 * */
	var MOD_NAME = 'schema_render',
		$ = layui.jquery,
        editor = layui.editor,
		api = layui.api,
        listener = layui.listener,
        action_executer = layui.action_executer,
        amis = layui.amis,
        utils = layui.utils,
        dialogDivElem = "[role='dialog']"
        // dialogDivElem = ".amis-dialog-widget"
    ;

	var schema_render = function(opt) {
		this.option = opt;
	};

    /**
     * 增加amis dialog主动关闭弹窗
     * @param {*} dialogSchema 
     */
    function insertDialogClose(dialogSchema){
        insertFormSuccessClose(dialogSchema)
        cancelDialogClose(dialogSchema)
        // function closeAmisDialog(){
            // $(".cxd-Modal-close").unbind('click');
            // $(".cxd-Modal-close").click(function(){
            //     // 解决点击X号爆红问题
            //     debugger
            //     if($(dialogDivElem).length>0){
            //         console.log($(dialogDivElem).length,$(dialogDivElem),'length')
            //         if($(dialogDivElem).length == 1){
            //             $('#app #amisDialogContent').remove()
            //             // clearInterval(interval)
            //         } else {
            //             $(this).parents('.cxd-Modal').remove()
            //         }
            //         console.log($(dialogDivElem).length,'length')
                    
            //         // if($(dialogDivElem).length === 1){
            //         //     $(dialogDivElem).remove();
            //         //     $('#app #amisDialogContent').remove()
            //         //     clearInterval(interval)
            //         // } else {
            //         //    $(this).parents('.cxd-Modal').remove()
            //         // }
            //     }
            // })

        // }()
        // debugger
        //增加定时器读取是否渲染完弹窗，
        var interval = setInterval(function(){
            $(".cxd-Modal-close").unbind('click');
            $("#amisDialogContent .cxd-Modal-close").click(function(){
                // 解决点击X号爆红问题
                if($(dialogDivElem).length>0){

                    console.log($(dialogDivElem).length,$(dialogDivElem),'length')
                    if($(dialogDivElem).length == 1){
                        $('#app #amisDialogContent').remove()
                        clearInterval(interval)
                    } else {
                        // 什么都不用处理竟然好用了，神奇
                        // $(this).parents('.cxd-Modal').remove()
                    }
                    console.log($(dialogDivElem).length,'length')
                }


                // 点击一个X号，清除所有弹框，目前最好的方案可用
                // if($(dialogDivElem).length>0){
                //     console.log($(dialogDivElem).length,'length')
                //     $(dialogDivElem).remove();
                //     $('#app #amisDialogContent').remove()
                //     clearInterval(interval)
                // }

            })

        },200)
        
        // setTimeout(function(){
        //     clearInterval(interval)
        // },2000); 
    }

    /**
     * amis dialog表单提交成功后不会主动关闭窗口，需要主动删除弹窗
     * @param {} dialogSchema 
     */
    function insertFormSuccessClose(dialogSchema){
        $.each(dialogSchema.body, function(i, item){
            if(item.type === 'form'){
                if(item.onEvent){
                    if(item.onEvent.submitSucc){
                        item.onEvent.submitSucc.actions.push(
                            getFormSuccessSchema()
                        )
                    }else{
                        item.onEvent.submitSucc = {
                            "weight": 0,
                            "actions": [
                                getFormSuccessSchema()
                            ]
                          }
                    }
                }else{
                    item.onEvent = {
                        "submitSucc": {
                          "weight": 0,
                          "actions": [
                            getFormSuccessSchema()
                          ]
                        }
                      }
                }
            }
        })
    }

    function getFormSuccessSchema(){
        // var script = `
        // $(\"${dialogDivElem}\").remove();
        // $('#app #amisDialogContent').remove();
        // var data = event.context.data.result.data;
        // var callback = layui.utils.callback;
        // if (callback && callback.dialog && typeof callback.dialog === 'function') {
        //     callback.dialog(data);
        // }
        // setTimeout(function(){
        //     $('#app #amisDialogContent').remove();
        // },2000)
        // `;
        var script = `
        $(\"${dialogDivElem}\").remove();
        var data = event.context.data.result.data;
        var callback = layui.utils.callback;
        if (callback && callback.dialog && typeof callback.dialog === 'function') {
            callback.dialog(data);
        }
        setTimeout(function(){
           $('#app #amisDialogContent').remove();
        },2000)
        `;
        return {
            "actionType": "custom",
            "script": script
        }
    }

    function getCloseActionSchema(){
        return {
            "actionType": "custom",
            // "script": "$(\""+dialogDivElem+"\").remove();$('#app #amisDialogContent').remove()",
            "script": `$(\"${dialogDivElem}\").remove();$('#app #amisDialogContent').remove();`
          };
    }


    /**
     * amis dialog弹窗取消时不会主动关闭窗口，需要主动删除弹窗
     * @param {} dialogSchema 
     */
     function cancelDialogClose(dialogSchema){
        if(dialogSchema.onEvent){
            if(dialogSchema.onEvent.cancel){
                dialogSchema.onEvent.cancel.actions.push(
                    getCloseActionSchema()
                )
            }else{
                dialogSchema.onEvent.cancel = {
                    "weight": 0,
                    "actions": [
                        getCloseActionSchema()
                    ]
                  }
            }
        }else{
            dialogSchema.onEvent = {
                "cancel": {
                  "weight": 0,
                  "actions": [
                    getCloseActionSchema()
                  ]
                }
              }
        }
    }

    function renderDialog(dialog, option){
        // $('body').addClass('amis-scope')
        function removeBodyClass(){
            $('body').removeClass('amis-scope')
        }
        layer.open({
            type:1,
            // area:['20%','200px'],
            title: dialog.title,
            offset: '30%',
            zIndex: 100,
            content: "<div id='testDialogContent' style='width: "+dialog.width+"; height: "+dialog.height+"' align='center'></div>",
            shade: 0.3,
            btn: ['提交', '取消'],
            btn1:function (index, layero) {
                var amis = option;
                //验证表单
                var va = amis.funcAmis.option.amisScoped.getComponentById("modelForm").validate();

                var formObject = amis.funcAmis.option.amisScoped.getComponentByName("modelForm").getValues();
                
                var optionApi = amis.funcAmis.option.schema.api;

                if(optionApi.data!=undefined && optionApi.data!=null){
                    if( typeof optionApi.data =='string'){
                        optionApi.data = optionApi.submitData;
                    }else{
                        optionApi["submitData"] = optionApi.data;
                    }
                }

                execApi({
                    optionApi : optionApi,
                    execData : formObject,
                    contextData: option.contextData,
                    success: function(data){
                        if(option.callback && option.callback.dialog && typeof option.callback.dialog === 'function'){
                            option.callback.dialog(data);
                        }
                        layer.closeAll();
                        // removeBodyClass()
                        layer.msg('操作成功');
                    }
                })
            },
            btn2: function(){
                // removeBodyClass()
            },
            cancel: function(layero,index){
                layer.closeAll();
                // removeBodyClass()
            }

        });
    }


    function formatApiOptionData(optionApi, execData){
        // var data = JSON.parse(JSON.stringify(optionApi.data).format(execData));
        var data = JSON.parse(utils.stringformat(JSON.stringify(optionApi.data),execData));
        if(data['&'] === '$$'){
            $.extend(data, execData["mid"]);
            delete data['&'];
        }
        $.extend(data, execData);
        return data
    }

    function formatUrl(url, contextData){
        //url替换
        // return url.format(contextData);
        return utils.stringformat(url,contextData);
    }

    function beforeExecHandle(optionApi){
        if(optionApi.type !== 'get'){
            optionApi.contentType = 'application/json;charset=UTF-8';
            optionApi.data = JSON.stringify(optionApi.data);
        }
    }


    function execApi(apiOpt){
        var {optionApi, execData, success, } = apiOpt
        var data = apiOpt.contextData.data;
        if(typeof optionApi === 'object'){
            //模版数据替换
            var apiOption = optionApi;
            //url替换
            apiOption.url = utils.stringformat(apiOption.url, data);
            apiOption.data = formatApiOptionData(optionApi, execData);
            apiOption.success = success;

            //执行前处理
            beforeExecHandle(optionApi);
            api.exec(apiOption);
        }else{
            optionApi = utils.stringformat(optionApi,data)

            var method=optionApi.slice(0,optionApi.indexOf(":"));
            var apiUrl=optionApi.slice(optionApi.indexOf(":")+1);
            if(method =='http' || optionApi.indexOf(":")==-1){
                method = 'get';
                apiUrl = optionApi;
            }

            var optionApi = {
                type: method,
                url: formatUrl(apiUrl, data),
                data: execData,
                success
            };

            //执行前处理
            beforeExecHandle(optionApi);
            api.exec(optionApi)
        }
    }

    /**
     弹出iframe页面(iframe后面会添加灰色蒙版)
     **/
    function showIframe(url,contentElem,w,h){
        var frameId = contentElem.slice(1) + '_YuFrame1';

        //添加iframe
        var if_w = w;
        var if_h = h;
        //allowTransparency='true' 设置背景透明
        $("<iframe width='100%' height='100%' id="+frameId+" name="+frameId+" style='position:absolute;'  frameborder='no' marginheight='0' marginwidth='0' allowTransparency='true'></iframe>").prependTo(contentElem);
        var st=document.documentElement.scrollTop|| document.body.scrollTop;//滚动条距顶部的距离
        var sl=document.documentElement.scrollLeft|| document.body.scrollLeft;//滚动条距左边的距离
        var ch=document.documentElement.clientHeight;//屏幕的高度
        var cw=document.documentElement.clientWidth;//屏幕的宽度
        var objH=$("#" + frameId).height();//浮动对象的高度
        var objW=$("#" + frameId).width();//浮动对象的宽度
        var objT=Number(st)+(Number(ch)-Number(objH))/2;
        var objL=Number(sl)+(Number(cw)-Number(objW))/2;
        $("#" + frameId).css('left',0);
        $("#" + frameId).css('top',40);

        $("#" + frameId).attr("src", url)

        //添加背景遮罩
        var frameById = contentElem.slice(1) + '_YuFrame1Bg';
        $("<div id='YuFrame1Bg' style='display:block;z-index:3;position:absolute;left:0px;top:0px;filter:Alpha(Opacity=30);/* IE */-moz-opacity:0.4;/* Moz + FF */opacity: 0.4; '/>").prependTo(contentElem);
        var bgWidth = Math.max($("body").width(),cw);
        var bgHeight = Math.max($("body").height(),ch);
        $("#" + frameById).css({width:bgWidth,height:bgHeight});

        //点击背景遮罩移除iframe和背景
        $("#" + frameById).click(function() {
            $("#" + frameId).remove();
            $("#" + frameById).remove();
        });
    }




    /**
	 * Button start loading
	 * */
     schema_render.prototype.render = function(opt) {

         //debugger
		var option = {
            elem: opt.elem,
            schema: opt.schema,
            submit: opt.submit,
            contextData: opt.contextData,
            callback: opt.callback
		}

        var data = {};
        if(option.contextData){
            data = utils.getGlobalEnv(option.contextData.data);
        }
        
        var schema = option.schema;

        if(schema.mode && schema.mode === 'listener'){
            var id = schema.elem;
            var listenerName;
            if(schema.listenerName){
                listenerName = schema.listenerName;
            }else{
                listenerName = id + '_contextMenu_listener';
            }
            var contextMenuListener = listener.getContextMenuListener(listenerName);
            if(contextMenuListener &&  typeof contextMenuListener === 'function'){
                contextMenuListener(data, schema)
            }

        }
        else if(schema.mode && schema.mode === 'amis_dialog'){
            console.log('222222')
            var amisDialogContentId = "amisDialogContent";
            // console.log($("#app #" + amisDialogContentId).size(),'$("#app #" + amisDialogContentId).size()')
            if($("#app #" + amisDialogContentId).size() == 0){
                // 必须在app的盒子前边追加进去
                $("#app").prepend(`
                    <div id='${amisDialogContentId}'></div>
                `);
            }

            // // 置空新增表单同名数据
            data["name"] = null;
            data["enName"] = null;
            var amisSchema = schema.amisSchema;
            var amisSchemaApi = schema.amisSchemaApi;

            var dialogSchema;

            //需要特殊处理schema的弹窗关闭，所以如果是schemaApi的传入，要提前获取
            if(amisSchema){
                dialogSchema = amisSchema;
            }else if(amisSchemaApi){
                api.get({
                    type: "GET",
                    url: amisSchemaApi,
                    async: false,
                    success: function(data){
                        dialogSchema = JSON.parse(data);
                    }
                })
            }

            //临时存放弹窗成功回调函数
            utils.callback = option.callback;

            //拷贝一个新的schema对象
            var cloneSchema = $.extend(true, cloneSchema, dialogSchema)
            //增加amis dialog主动关闭弹窗
            insertDialogClose(cloneSchema);
            console.log(amisDialogContentId,'amisDialogContentId')

            // debugger
            var amisNew = amis.render({
                elem: '#' + amisDialogContentId,
                schema: cloneSchema,
                props:{
                    data:data
                }
                // extension: extension
            })

            

            option.funcAmis = amisNew;  
        }
        else if(schema.mode && schema.mode === 'dialog'){
            console.log('1111111')
            var dialog = schema.dialog;
            // 置空新增表单同名数据
            // data["name"] = null;
            // data["enName"] = null;
            if(dialog.mode === 'amis'){
                
                renderDialog(dialog, option);
                var amisSchema = dialog.amisSchema;
                var amisSchemaApi = dialog.amisSchemaApi;

                // debugger
                var amisNew = amis.render({
                    elem: '#testDialogContent',
                    schema: amisSchema,
                    schemaApi: amisSchemaApi,
                    props:{
                        data:data
                    }
                })

                option.funcAmis = amisNew;
            }
        }else if(schema.mode && schema.mode === 'ajax'){
            var optionApiStr = schema.api;

            if(optionApiStr.data!=undefined && optionApiStr.data!=null){
              if( typeof optionApiStr.data =='string'){
                  optionApiStr.data = optionApiStr.submitData;
               }else{
                  optionApiStr["submitData"] = optionApiStr.data;
               }
            }

            function _execApi(){
                execApi({
                    optionApi : optionApiStr,
                    execData : data,
                    contextData: option.contextData,
                    success: function(data){
                        layer.msg('操作成功');
                        if(option.callback && option.callback.dialog && typeof option.callback.dialog === 'function'){
                            option.callback.dialog(data);
                        }
                    }
                })
            }

            if(schema.confirmText){
                layer.confirm(schema.confirmText, function(index){
                    _execApi()
                  });
            }else{
                _execApi();
            }

            
        }else if(schema.mode === 'amis'){
            
            var amisSchema = schema.amisSchema;
            var amisSchemaApi = schema.amisSchemaApi;
            // data["name"] = null;
            // data["enName"] = null;
            if(amisSchemaApi!=undefined){
                amisSchemaApi = utils.stringformat(amisSchemaApi,data);
            }
            amis.render({
                elem: option.elem,
                schema: amisSchema,
                schemaApi: amisSchemaApi,
                props:{
                    data:data
                }
            })
        }else if(schema.mode === 'iframe'){
            var iframeUrl = utils.stringformat(schema.url,data);
            showIframe(iframeUrl,option.elem);
        }else if(schema.mode === 'action'){
            var actionSchema = schema.action;
            action_executer.exec({
                elem: option.elem,
                schema: actionSchema,
                data: data
            })
        }else if(schema.mode ==='open'){
            window.open(utils.stringformat(schema.url,data));
        }

        return new schema_render(option);
	}


    exports(MOD_NAME, new schema_render());
});
